<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat App</title>
    <!-- SocketIO JavaScript library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
</head>
<body>

<div>
    <h1>Chat App</h1>
    <div id="chat-box" style="height: 300px; overflow: auto; border: 1px solid #ccc; padding: 10px;"></div>
    <input type="text" id="message-input" placeholder="Enter your message">
    <button onclick="sendMessage()">Send</button>
</div>

<script>
    // Connect to SocketIO server
    const socket = io.connect('https://8.130.98.122:8765');

    // Function to send a message to the server
    function sendMessage() {
        const messageInput = document.getElementById('message-input');
        const message = messageInput.value;
        
        // Append user's message to the chat box
        appendMessage('You：', message);
        
        // Emit the message to the server
        socket.emit('message', { message });
        
        // Clear the input field
        messageInput.value = '';
    }

    // Function to handle incoming messages from the server
    socket.on('message', function(data) {
        // Append the incoming message to the chat box
        appendMessage('',data.data);
    });

    // Function to append a message to the chat box
    function appendMessage(sender, message) {
        const chatBox = document.getElementById('chat-box');
        chatBox.innerHTML += `<p><strong>${sender}</strong> ${message}</p>`;
        chatBox.scrollTop = chatBox.scrollHeight;  // Scroll to the bottom of the chat box
    }

    // Handle page unload or close event
    socket.on('disconnected', function () {
        // Handle disconnect event if needed
    });
</script>

</body>
</html>
